package com.kejiguan.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import com.kejiguan.ui.adapter.HomeMenuAdapter;
import com.kejiguan.ui.dialog.AlarmDialog;
import com.kejiguan.ui.dialog.AlarmDialogUtil;
import com.kejiguan.ui.dialog.CommDialogUtil;
import com.kejiguan.ui.event.OnKeyOperationEvent;
import com.kejiguan.ui.event.OnOroffEvent;
import com.kejiguan.ui.model.MenuItem;
import com.kejiguan.ui.presenter.MainActivityPresenter;
import com.kejiguan.ui.presenter.QueryExStateEvent;
import com.kejiguan.ui.response.AlarmResponse;
import com.kejiguan.ui.util.CacheDataUtil;
import com.kejiguan.ui.util.PostNotifycation;
import com.kejiguan.ui.widget.MyLinearLayoutManager;
import com.kejiguan.ui.widget.SpacesItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by apple on 16/3/2.
 */
public class MainActivity extends BaseFragmentActivity implements View.OnClickListener, AlarmDialog.OnAlarmDialogDismissListener {

    private DrawerLayout drawerLayout;
    private RecyclerView menuList;
    private HomeMenuAdapter menuAdapter;

    private EasyShuttleFragment easyShuttleFragment;//          一键开关机
    private DisplayFragmentNew displayFragment;//单个开关机
    private NeItemRunDataFragment neItemRunDataFragment;//状态监测
    private FragmentDataStatistics dataStatistics;//状态监测
    private DisplaySettingFragment settingFragment;//展区设置
    private NeIitemManagerFragment neIitemManagerFragment;
    private UserManagerFragment userManagerFragment;//用户管理
    private UserInfoFragment userInfoFragment;//个人信息
    private TimingScheduleSettingFragment timingScheduleSettingFragment;//定时开关机设置

    private MainActivityPresenter mPresenter;
    private Timer timer, timer1;

    private AlarmResponse alarmResponse;

    @Override
    public void onCreate(Bundle bundle) {
        Log.e(MainActivity.class.getSimpleName(), "onCreate");
        super.onCreate(bundle);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_main_layout_new);
        mPresenter = new MainActivityPresenter();
        mPresenter.onCreate(MainActivity.this);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawe_layout);
        menuList = (RecyclerView) findViewById(R.id.menu_list);
        MyLinearLayoutManager manager = new MyLinearLayoutManager(MainActivity.this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        menuList.setLayoutManager(manager);
        menuAdapter = new HomeMenuAdapter(MainActivity.this, CacheDataUtil.getInstance().getMenuItems());
        menuAdapter.setOnClickListener(this);
        menuList.addItemDecoration(new SpacesItemDecoration(52, false));
        menuList.setAdapter(menuAdapter);

        if (menuAdapter.getSelectArea() != null) {
            switch (menuAdapter.getSelectArea().getMenuId()) {
                case 201://一键开机
                    easyShuttleFragment = new EasyShuttleFragment();
                    addFragment(R.id.fragment_contant, easyShuttleFragment);
                    break;
                case 202://单个开关机
                    displayFragment = new DisplayFragmentNew();
                    addFragment(R.id.fragment_contant, displayFragment);
                    break;
                case 203://状态检测
                    neItemRunDataFragment = new NeItemRunDataFragment();
                    addFragment(R.id.fragment_contant, neItemRunDataFragment);
                    break;
                case 204://定时调度
                    timingScheduleSettingFragment = new TimingScheduleSettingFragment();
                    addFragment(R.id.fragment_contant, timingScheduleSettingFragment);
                    break;
                case 205://展区设置
                    settingFragment = new DisplaySettingFragment();
                    addFragment(R.id.fragment_contant, settingFragment);
                    break;
                case 208://展区设置
                    dataStatistics = new FragmentDataStatistics();
                    addFragment(R.id.fragment_contant, dataStatistics);
                    break;
                case 209://展区设置
                    neIitemManagerFragment = new NeIitemManagerFragment();
                    addFragment(R.id.fragment_contant, neIitemManagerFragment);
                    break;
                case 503://用户管理
                    userManagerFragment = new UserManagerFragment();
                    addFragment(R.id.fragment_contant, userManagerFragment);
                    break;
                case 504://个人信息
                    userInfoFragment = new UserInfoFragment();
                    addFragment(R.id.fragment_contant, userInfoFragment);
                    break;

            }
        }
        alarmResponse = (AlarmResponse) getIntent().getSerializableExtra("alarm_info");
        if (null == alarmResponse) {
            Log.e(MainActivity.class.getSimpleName(), "onCreate: alarmResponse为空");
        } else {
            Log.e(MainActivity.class.getSimpleName(), "onCreate: alarmResponse不为空");
        }

        startCheckNeItemsState();
        startCheckAlarmInfos();
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timer1 != null) {
            timer1.cancel();
            timer1 = null;
        }
    }


    TimerTask checkNeItemsStateTask = new TimerTask() {
        @Override
        public void run() {
            mPresenter.checkNeItemsState();
        }
    };

    TimerTask checkAlarmInfos = new TimerTask() {
        @Override
        public void run() {
            mPresenter.checkAlarmInfos();
        }
    };

    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.e(MainActivity.class.getSimpleName(), "onNewIntent: .");
        alarmResponse = (AlarmResponse) intent.getSerializableExtra("alarm_info");
        if (null == alarmResponse) {
            Log.e(MainActivity.class.getSimpleName(), "onNewIntent: alarmResponse为空");
        } else {
            Log.e(MainActivity.class.getSimpleName(), "onNewIntent: alarmResponse不为空");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        drawerLayout.closeDrawers();
        Log.e(MainActivity.class.getSimpleName(), "onResume: .");
        if (null == alarmResponse) {
            Log.e(MainActivity.class.getSimpleName(), "onResume: alarmResponse为空");
        } else {
            Log.e(MainActivity.class.getSimpleName(), "onResume: alarmResponse不为空");
        }
        if (null != alarmResponse) {
            Intent alarmIntent=new Intent(MainActivity.this,ActivityAlarm.class);
            alarmIntent.putExtra("alarmcontent",alarmResponse.getAlarmContent());
            startActivity(alarmIntent);
            alarmResponse=null;
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {

            CommDialogUtil.getInstance().show(MainActivity.this, "要退出掌上中控系统吗？", MainActivity.this, "退出", "取消", 0);
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.menu_item:
                int pisition = (int) v.getTag(R.id.recyclerview_item_position);
                menuAdapter.setSelectMenu(pisition);
                MenuItem menuItem = menuAdapter.getMenu(pisition);
                switch (menuItem.getMenuId()) {
                    case 201://一键开机
                        if (easyShuttleFragment == null) {
                            easyShuttleFragment = new EasyShuttleFragment();
                        }
                        showFragment(easyShuttleFragment);
                        drawerLayout.closeDrawers();
                        break;
                    case 202://单个开关机
                        if (displayFragment == null) {
                            displayFragment = new DisplayFragmentNew();
                        }
                        showFragment(displayFragment);
                        drawerLayout.closeDrawers();
                        break;
                    case 203:
                        if (neItemRunDataFragment == null) {
                            neItemRunDataFragment = new NeItemRunDataFragment();
                        } else {
                            neItemRunDataFragment.reLoad();
                        }
                        showFragment(neItemRunDataFragment);
                        drawerLayout.closeDrawers();
                        break;
                    case 204://定时调度
                        if (timingScheduleSettingFragment == null) {
                            timingScheduleSettingFragment = new TimingScheduleSettingFragment();
                        }
                        showFragment(timingScheduleSettingFragment);
                        drawerLayout.closeDrawers();
                        break;
                    case 205://展区设置
                        if (settingFragment == null) {
                            settingFragment = new DisplaySettingFragment();
                        }
                        showFragment(settingFragment);
                        drawerLayout.closeDrawers();
                        break;
                    case 208:
                        if (dataStatistics == null) {
                            dataStatistics = new FragmentDataStatistics();
                        }
                        showFragment(dataStatistics);
                        break;
                    case 209:
                        if (neIitemManagerFragment == null) {
                            neIitemManagerFragment = new NeIitemManagerFragment();
                        } else {
                            neIitemManagerFragment.reLoad();
                        }
                        showFragment(neIitemManagerFragment);
                        drawerLayout.closeDrawers();
                        break;
                    case 503://用户管理
                        if (null == userManagerFragment) {
                            userManagerFragment = new UserManagerFragment();
                        }
                        showFragment(userManagerFragment);
                        drawerLayout.closeDrawers();
                        break;
                    case 504://个人信息
                        if (null == userInfoFragment) {
                            userInfoFragment = new UserInfoFragment();
                        }
                        showFragment(userInfoFragment);
                        drawerLayout.closeDrawers();
                        break;
                }
                drawerLayout.closeDrawers();
                break;
            case R.id.title:
                break;
            case R.id.dialog_confirm_btn:
                CommDialogUtil.getInstance().dismiss();
                System.exit(0);
                break;
            case R.id.dialog_cancel_btn:
                CommDialogUtil.getInstance().dismiss();
                break;
            case R.id.alarm_ok_btn:
                AlarmDialogUtil.getInstance().dismiss();
                Intent alarmIntent = new Intent(MainActivity.this, ActivityAlarm.class);
                startActivity(alarmIntent);
                break;

        }
    }


    public void startCheckNeItemsState() {
        if (timer == null) {
            timer = new Timer("检查设备运行状态定时器");
            timer.schedule(checkNeItemsStateTask, 5000, 10000);//每15秒调用一次接口
        }
    }

    public void startCheckAlarmInfos() {
        if (timer1 == null) {
            timer1 = new Timer("检查设备运行状态定时器");
            timer1.schedule(checkAlarmInfos, 6000, 90000);//每15秒调用一次接口
        }

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(OnKeyOperationEvent response) {

        startCheckNeItemsState();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(OnOroffEvent response) {

        startCheckNeItemsState();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(QueryExStateEvent exStateEvent) {

        mPresenter.checkNeItemsState();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(
            AlarmResponse response) {
        if ("0000".equals(response.getRetCode()) && null != response.getAlarmContent()) {

            if (!TextUtils.isEmpty(response.getAlarmContent().trim())) {
                PostNotifycation.getInstance().showPostNotifycation(MainActivity.this, response);
            }
        }

    }

    @Override
    public void onAlarmDismiss() {
        alarmResponse = null;
    }


    public void closeSlidingMenu() {

        drawerLayout.closeDrawers();
    }

    public void hideStateLayout() {

    }

    public void showStateLayout() {

    }


}
